package com.emex.app.stuff.gui;

import com.emex.app.shared.data.Client;
import com.emex.app.shared.data.OrderPayment;
import com.emex.app.shared.data.enums.PayMethod;
import com.emex.app.stuff.security.SecurityManager;
import com.emex.app.stuff.gui.model.OrderPaymentTableModel;
import com.emex.app.stuff.provider.OrderDataProvider;
import com.emex.app.stuff.utils.DateUtils;
import com.emex.app.stuff.utils.UIUtils;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;

/**
 *
 * @author Sergey Karavaev
 */
public class OrderPaymentDialog extends javax.swing.JDialog {

    private OrderPayment orderPayment;

    private OrderPaymentTableModel tableModelToUpdate;

    private Client client;

    /**
     * Creates new form OrderPaymentDialog
     */
    public OrderPaymentDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        payMethodComboBox.setModel(new DefaultComboBoxModel(PayMethod.values()));
        datePicker.setFormats(DateUtils.getSimpleDateFormat());
        datePicker.setDate(new Date());
    }

    public void setOrderPayment(OrderPayment orderPayment) {
        this.orderPayment = orderPayment;

        if (null != orderPayment) {
            datePicker.setDate(orderPayment.getDate());
            summaField.setText(orderPayment.getSumma().toString());
            payMethodComboBox.setSelectedItem(PayMethod.valueOf(orderPayment.getPayMethod()));
            if (null != orderPayment.getComment()) {
                commentArea.setText(orderPayment.getComment());
            }
        }
    }

    public void setClient(Client client) {
        this.client = client;
    }

    public void setTableModelToUpdate(OrderPaymentTableModel tableModelToUpdate) {
        this.tableModelToUpdate = tableModelToUpdate;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        datePicker = new org.jdesktop.swingx.JXDatePicker();
        summaField = new javax.swing.JTextField();
        payMethodComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        commentArea = new javax.swing.JTextArea();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(OrderPaymentDialog.class, "OrderPaymentDialog.title")); // NOI18N
        setResizable(false);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(OrderPaymentDialog.class, "OrderPaymentDialog.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(OrderPaymentDialog.class, "OrderPaymentDialog.jLabel2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(OrderPaymentDialog.class, "OrderPaymentDialog.jLabel3.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(OrderPaymentDialog.class, "OrderPaymentDialog.jLabel4.text")); // NOI18N

        summaField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        summaField.setText(org.openide.util.NbBundle.getMessage(OrderPaymentDialog.class, "OrderPaymentDialog.summaField.text")); // NOI18N

        commentArea.setColumns(20);
        commentArea.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
        commentArea.setRows(5);
        jScrollPane1.setViewportView(commentArea);

        org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(OrderPaymentDialog.class, "OrderPaymentDialog.saveButton.text")); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(OrderPaymentDialog.class, "OrderPaymentDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(21, 21, 21)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(payMethodComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(summaField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                            .addComponent(datePicker, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addGap(15, 15, 15)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(datePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(summaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(payMethodComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        boolean operationCreate = false;

        if (orderPayment == null) {
            orderPayment = new OrderPayment();
            operationCreate = true;
        }

        if (null == datePicker.getDate()) {
            UIUtils.showErrorMessage("Заполните дату оплаты");
            return;
        }
        if (summaField.getText().isEmpty()) {
            UIUtils.showErrorMessage("Заполните внесенную сумму");
            return;
        }
        if (null == payMethodComboBox) {
            UIUtils.showErrorMessage("Выберите способ оплаты");
            return;
        }

        orderPayment.setDate(datePicker.getDate());
        orderPayment.setSumma(Double.valueOf(summaField.getText().replaceAll(",", ".")));
        PayMethod payMethod = (PayMethod) payMethodComboBox.getItemAt(payMethodComboBox.getSelectedIndex());
        orderPayment.setPayMethod(payMethod.ordinal());
        orderPayment.setComment(commentArea.getText());

        if (operationCreate) {
            orderPayment.setManagerId(SecurityManager.getDefault().getCurrentPerson().getId());
            orderPayment.setName("Оплата заказа от " + DateUtils.getExtendedFormattedString(datePicker.getDate()));
            if (null != client) {
                orderPayment.setClientId(client.getId());
                orderPayment = OrderDataProvider.getInstance().insertOrderPayment(orderPayment);
            }
            tableModelToUpdate.dataAdded(orderPayment);
        } else {
            if (null != client) {
                OrderDataProvider.getInstance().updateOrderPaymentByPrimaryKey(orderPayment);
            }
            tableModelToUpdate.dataUpdated();
        }

        this.setVisible(false);
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OrderPaymentDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OrderPaymentDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OrderPaymentDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OrderPaymentDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                OrderPaymentDialog dialog = new OrderPaymentDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextArea commentArea;
    private org.jdesktop.swingx.JXDatePicker datePicker;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox payMethodComboBox;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField summaField;
    // End of variables declaration//GEN-END:variables
}
